package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.cloud.iov.common.flow.view.impl.BaseLoadingFlowView;
import com.tencent.cloud.iov.flow.presenter.IPresenter;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.service.TXStorageService;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.BitmapUtils;
import com.tencent.cloud.iov.util.FileUtils;
import com.tencent.cloud.iov.util.FragmentUtils;
import com.tencent.cloud.iov.util.PhotoBitmapUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.SHAUtils;
import com.tencent.cloud.uikit.ui.widget.IovToolbar;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.cloud.uikit.utils.PermissionUtils;
import com.tencent.cloud.uikit.utils.SystemUiUtils;
import com.tencent.cloud.uikit.widget.dialog.BottomSheetDialog;
import com.tencent.cloud.uikit.widget.edittext.LineEditText;
import com.tencent.tac.storage.StorageResultListener;
import com.tencent.tac.storage.TACStorageReference;
import com.tencent.tac.storage.TACStorageTaskSnapshot;

import java.io.File;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActionConst;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountCommonConst;
import cn.sirun.com.fca.account.constant.RequestParamConst;
import cn.sirun.com.fca.account.fragment.CameraFragment;

public class OwnerAuthCarFlowView extends BaseLoadingFlowView {

    private LineEditText mOwnerET, mVinET;
    private ImageView mOwnerPromptIV, mVinIV;
    private TextView mOwnerTV, mVinTV, mNextTV;
    private View mOwnerLineV, mVinLineV;

    private ImageView mIdCardFront;


    private FragmentManager mFragmentManager;
    private Fragment mCurrentFragment;

    /**
     * 头像文件名称缓存key
     */
    private String mImageFileNameCacheKey;

    /**
     * 头像文件名称
     */
    private String mImageFileName;

    /**
     * 更新头像过程中，临时文件名称
     */
    private String mImageTempFileName;



    private String mHeadPortraitFilePath;


    private Bitmap mHeadPortraitBitmap;

    private Matrix mMatrix = new Matrix();

    private AsyncTask<Bitmap, Void, File> mUploadPortraitTask;



    private CameraFragment mCameraFragment;


    public OwnerAuthCarFlowView(Activity activity) {
        super(activity);
    }

    public OwnerAuthCarFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }

    private void setUpActionBar() {
        final Activity activity = getActivity();
        final IovToolbar toolbar = SystemUiUtils.showActionBar(
                activity, "");
        toolbar.setHomeAsUpText(R.string.tv_title_upback);

    }

    private void initView() {
        setContentView(R.layout.owner_auth_car_activity);

        mFragmentManager = ((AppCompatActivity) getActivity()).getSupportFragmentManager();


        final Activity activity = getActivity();

//        mNextTV = activity.findViewById(R.id.tv_next);
//        mIdCardFront = activity.findViewById(R.id.img_idcard_front);

        turnToCameraFragment(false);

        mIdCardFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//                openCamera();

                turnToCameraFragment(false);

               /* final BottomSheetDialog bottomSheetDialog
                        = new BottomSheetDialog(getActivity());

                View.OnClickListener listener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (R.id.btn_take_photo == id) {
                            openCamera();
                        } else if (R.id.btn_photo_album == id) {
                            ActivityUtils.openAlbum(getActivity(),
                                    AccountCommonConst.PHOTO_FROM_ALBUM_REQUEST_CODE);
                        }
                        bottomSheetDialog.dismiss();
                    }
                };

                bottomSheetDialog.setClickListener(listener);
                bottomSheetDialog.show();*/

            }
        });

        mNextTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = Router.fromPath(AccountActivityConst.Path.OWNER_BELONGTO_CAR);
                ActivityUtils.startActivity(activity, intent);
            }
        });
    }







    private void openCamera() {
        if (!PermissionUtils.hasCameraPermissions(getActivity())) {
            PermissionUtils.requestCameraPermissions(getActivity());
            return;
        }

        mImageTempFileName = System.currentTimeMillis() + ".jpg";
        ActivityUtils.openCamera(getActivity(),
                AccountActionConst.Normal.PHOTO_FROM_CAMERA_REQUEST_CODE,
                mImageTempFileName);
    }




    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Activity.RESULT_OK == resultCode) {
            if (AccountCommonConst.PHOTO_FROM_ALBUM_REQUEST_CODE == requestCode) {
                Uri uri = data.getData();
                String filePath = BitmapUtils.getRealPathFromUri(getActivity(), uri);
//                setHeadPortraitFromAlbum(filePath);
            } else if (AccountActionConst.Normal.PHOTO_FROM_CAMERA_REQUEST_CODE == requestCode) {
                setHeadPortraitFromCamera();
            }
        } else if (PermissionUtils.isSettingsPermissionRequest(requestCode)) {
            if (PermissionUtils.hasCameraPermissions(getContext())) {
                openCamera();
            } else {
                DialogUtils.showToast(getActivity(), R.string.request_camera_permission_failed);
            }
        }
    }



    public void setHeadPortraitFromCamera() {
        StringBuilder filePath = new StringBuilder();
        filePath.append(getActivity().getExternalCacheDir().getAbsolutePath())
                .append("/").append(mImageTempFileName);
        mHeadPortraitFilePath = filePath.toString();
        Log.e("xqm",""+mHeadPortraitFilePath);

        updateHeadPortrait();
    }



    private void updateHeadPortrait() {
//        updateActivityLayout(true);
        mIdCardFront.post(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(mHeadPortraitFilePath)) {
                    int angle = PhotoBitmapUtils.readPictureDegree(mHeadPortraitFilePath);
                    Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
                            mHeadPortraitFilePath,
                            mIdCardFront.getWidth(),
                            mIdCardFront.getHeight());
                    if (null == bitmap) {
                        DialogUtils.showToast(getActivity(), "读取图片失败！");
                        return;
                    }
                    mHeadPortraitBitmap = PhotoBitmapUtils.rotatingImageView(angle, bitmap);
                } else {
                    mHeadPortraitBitmap = BitmapUtils.decodeSampledBitmapFromResource(
                            ResourcesUtils.getResources(),
                            R.drawable.act_icon_camera,
                            mIdCardFront.getWidth(),
                            mIdCardFront.getHeight());
                }
                mIdCardFront.setImageBitmap(mHeadPortraitBitmap);
//                initCropView();

                uploadHeadPortrait(mHeadPortraitBitmap);
                showLoadingView();

            }
        });
    }




    private void uploadHeadPortrait(final Bitmap bitmap) {
        if (mUploadPortraitTask != null) {
            mUploadPortraitTask.cancel(false);
        }

        mUploadPortraitTask = new UploadHeadPortraitTask().execute(bitmap);
    }





    private void initCropView() {
        mIdCardFront.setScaleType(ImageView.ScaleType.CENTER);
//        mIdCardFront.setOnTouchListener(OwnerAuthCarFlowView.this);
        mIdCardFront.setScaleType(ImageView.ScaleType.MATRIX);
        adjustPreviewHeadPortraitLayout();
        mIdCardFront.setImageMatrix(mMatrix);
        mIdCardFront.setImageBitmap(mHeadPortraitBitmap);
    }


    /**
     * 调整预览头像布局
     * <p>
     * 参考ImageView configureBounds()[ScaleType.CENTER == mScaleType]实现
     */
    public void adjustPreviewHeadPortraitLayout() {
        int bitmapWidth = mHeadPortraitBitmap.getWidth();
        int bitmapHeight = mHeadPortraitBitmap.getHeight();
        int viewWidth = mIdCardFront.getWidth()
                - mIdCardFront.getPaddingLeft()
                - mIdCardFront.getPaddingRight();
        int viewHeight = mIdCardFront.getHeight()
                - mIdCardFront.getPaddingTop()
                - mIdCardFront.getPaddingBottom();
        mMatrix.setTranslate(Math.round((viewWidth - bitmapWidth) * 0.5f),
                Math.round((viewHeight - bitmapHeight) * 0.5f));
    }









    private class UploadHeadPortraitTask extends AsyncTask<Bitmap, Void, File> {

        @Override
        protected File doInBackground(Bitmap... bitmaps) {
            mImageTempFileName = System.currentTimeMillis() + ".jpg";
            File bitmapFile = new File(getActivity().getExternalCacheDir(), mImageTempFileName);
            if (!FileUtils.saveBitmap(bitmapFile, bitmaps[0])) {
                return null;
            }
            return bitmapFile;
        }

        @Override
        protected void onPostExecute(File bitmapFile) {
            if (bitmapFile == null) {
//                handleUploadResult(false);
                Log.e("xqm","上传成功");
                return;
            }

            String filePath = bitmapFile.getAbsolutePath();
            int fileType = RequestParamConst.ProFileOperateEnum.UPLOAD_PROFILE.getValue();
            String fileSHA256 = SHAUtils.sha256OfFile(filePath);

            // 上传监听器
            StorageResultListener<TACStorageTaskSnapshot> listener = new
                    StorageResultListener<TACStorageTaskSnapshot>() {

                        @Override
                        public void onSuccess(TACStorageTaskSnapshot tacStorageTaskSnapshot) {
                            // 组装图片url
                            TACStorageReference ref = tacStorageTaskSnapshot.getStorage();
                            String url = new StringBuilder("https://")
                                    .append(ref.getBucket())
                                    .append(".cos.")
                                    .append(ref.getRegion())
                                    .append(".myqcloud.com")
                                    .append(File.separator)
                                    .append(ref.getPath())
                                    .toString();

                            Log.e("xqm",""+url);

                            mImageFileNameCacheKey = ref.getPath().replace("/", "_");

                            // 调用access 上传图片url接口
                            if (null == getPresenter()) {
                                createPresenter();
                            }
//                            SubmitIconRequest request = new SubmitIconRequest();
//                            request.setUrl(url);
//                            getPresenter().submitIcon(request, mImageFileNameCacheKey);
                        }

                        @Override
                        public void onFailure(TACStorageTaskSnapshot tacStorageTaskSnapshot) {
                            if (null != tacStorageTaskSnapshot) {
                                tacStorageTaskSnapshot.getError().printStackTrace();
                            }
//                            handleUploadResult(false);
                            Log.e("xqm","上传失败");
                        }
                    };

            TXStorageService.getInstance().uploadFile(fileType, fileSHA256, filePath, listener);

        }

    }




    private void turnToCameraFragment(boolean isBack) {
        if (null == mCameraFragment) {
            mCameraFragment = new CameraFragment();
            mCameraFragment.setCameraListener(new CameraFragment.OnCameraListener() {
                @Override
                public void onTakePictureCallback(String filePath) {
//                    turnToOperateFragment(filePath, true);
                }

                @Override
                public void onBackPressed() {
//                    turnToOperateFragment(null, true);
                }
            });
        }
        mCameraFragment.setPictureType(RequestParamConst.PictureTypeEnum.IDENTITY_CARD);
//        if (switchFragment(mCameraFragment, isBack)) {
            mCameraFragment.checkPermissionOrStartPreview();
//        }
//        setAuthTitle(mPictureType);
    }






}
